/*************************************************
 * 
 * Copyright by Bruno Eberhard
 * 
 * Created on 05.08.2006
 *
 *************************************************/
package fightplan.business.util;

public class YearUtil {

	// possible year of a fighter: 1940 - 2039
	private static final int YEAR = 40;
	public static final int MIN_YEAR = 1900 + YEAR;
	public static final int MAX_YEAR = 2000 + YEAR - 1;
	public static final String ALL_YEAR = "Alle";

	public static int parse(String s) throws IllegalArgumentException {
		if (s == null)
			throw new IllegalStateException();
		s = s.trim();
		if (s.length() == 2) {
			int year = Integer.parseInt(s);
			if (year < YEAR) {
				return 2000 + year;
			} else {
				return 1900 + year;
			}
		} else if (s.length() == 4) {
			int year = Integer.parseInt(s);
			if (year < MIN_YEAR || year > MAX_YEAR)
				throw new IllegalArgumentException("Eine Jahreszahl muss zwischen " + MIN_YEAR + " und " + MAX_YEAR
						+ " liegen.");
			return year;
		} else {
			throw new IllegalArgumentException("Jahreszahlen müssen entweder 2 oder 4 Stellen besitzen.");
		}
	}

	public static int parseRangeStart(String s) throws IllegalArgumentException {
		if (s == null)
			throw new IllegalStateException(s);
		s = s.trim();
		if (ALL_YEAR.equals(s))
			return MIN_YEAR;
		int pos = s.indexOf("-");
		if (pos == 0)
			return MIN_YEAR;
		if (pos == -1)
			return parse(s);
		return parse(s.substring(0, pos));
	}

	public static int parseRangeEnd(String s) throws IllegalArgumentException {
		if (s == null)
			throw new IllegalStateException(s);
		s = s.trim();
		if (ALL_YEAR.equals(s))
			return MAX_YEAR;
		int pos = s.indexOf("-");
		if (pos == s.length() - 1)
			return MAX_YEAR;
		if (pos == 0)
			return parse(s.substring(1));
		return parse(s.substring(pos + 1, s.length()));
	}

	public static String format(int year) {
		return "" + year;
	}

	public static String formatRange(int start, int end) {
		if (start <= MIN_YEAR) {
			if (end >= MAX_YEAR) {
				return "Alle";
			} else {
				return "- " + end;
			}
		} else {
			if (end >= MAX_YEAR) {
				return start + " -";
			} else if (start == end) {
				return "" + start;
			} else {
				return start + " - " + end;
			}
		}
	}

}
